package com.crm.report.controller;

import com.crm.custinfo.service.impl.UserInfoComm;
import com.crm.dataReceive.domain.ReportCondition;
import com.crm.report.service.ICustStaticsService;
import com.ruoyi.common.constant.TypeConstant;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 客户数据统计
 *
 * @author Mr.Wen
 * @date 2024-02-25
 */
@RestController
@RequestMapping("/crmsys/custStatics")
public class CustStaticsController extends BaseController {
    @Autowired
    private ICustStaticsService iCustStaticsService;
    @Autowired
    private ISysDeptService isysDeptService;
    @Autowired
    private UserInfoComm userInfoComm;

    /**
     * 机构分配来源星级统计
     */
    @GetMapping("/getOrgDistributeDataStatics/{queryType}/{timeGroup}")
    public TableDataInfo getOrgDistributeDataStatics(@PathVariable String queryType, @PathVariable String timeGroup) {

        SysDept sysDept = getLoginUser().getUser().getDept();
        Long[] orgIds = userInfoComm.getSysDepts(sysDept);
        Map<String, Object> params = new HashMap<>();

        params.put("orgIds", orgIds);
        params.put("queryType", queryType);
        if (timeGroup != null && !timeGroup.isEmpty()) {
            String[] time = timeGroup.split(",");
            params.put("startTime", time[0]);
            params.put("endTime", time[1]+" 23:59:59");
        }
        List<Map<String, Object>> list = iCustStaticsService.orgDistributeDataStatics(params);

        return getDataTable(list);
    }
    /**
     * 机构分配来源星级统计
     */
    @PostMapping("/getChannelDataStatics")
    public TableDataInfo getChannelDataStatics(@RequestBody ReportCondition reportCondition ) {

        SysDept sysDept = getLoginUser().getUser().getDept();
        Long[] orgIds = userInfoComm.getSysDepts(sysDept);
        Map<String, Object> params = new HashMap<>();
        String channel_source=reportCondition.getChannel_source();
        String[] timeGroup=reportCondition.getTimeGroup();
        params.put("orgIds", orgIds);
        if (channel_source != null) {
            params.put("channel_source", channel_source);
        }
        if (timeGroup != null && timeGroup.length!=0) {
            String startTimeDate = timeGroup[0].split("T")[0];

            params.put("startTime", startTimeDate+" 00:00:00");
            String endTimeDate = timeGroup[1].split("T")[0];
            params.put("endTime", endTimeDate + " 23:59:59");
        }
        List<Map<String, Object>> list = iCustStaticsService.channelDataStatics(params);

        return getDataTable(list);
    }



    /**
     * 日内部数据统计
     */
    @GetMapping("/getDailyInnerDatas/{timeGroup}/{deptId}/{referrals}/{applyTime}")
    public TableDataInfo getDailyInnerDatas(@PathVariable String timeGroup, @PathVariable Long deptId, @PathVariable int referrals, @PathVariable String applyTime) {
        //获取登录账号的角色信息
        Map<String, Object> roleMap = userInfoComm.getUserRoleCode();

        Map<String, Object> params = new HashMap<>();
        SysDept sysDept = getLoginUser().getUser().getDept();
        if (Objects.equals(sysDept.getLevel(), String.valueOf(TypeConstant.ORG_LEVEL_4))) {
            if (MapUtils.getString(roleMap, "depart_leader", "0").equals("0")) { // 业务员
                // 业务员只能看到本人的日志
                params.put("empId", getUserId());
            }
        }
        if (deptId != -1L) {
            sysDept = new SysDept();
            sysDept.setDeptId(deptId);
        }

        Long[] orgIds = userInfoComm.getSysDepts(sysDept);
        params.put("orgIds", orgIds);
        if (timeGroup != null && !timeGroup.isEmpty()&& !timeGroup.equals("null")) {
            String[] time = timeGroup.split(",");
            params.put("startTime", time[0]);
            params.put("endTime", time[1]+" 23:59:59");
        }
        if (applyTime != null && !applyTime.isEmpty()&& !applyTime.equals("null")) {
            String[] time = applyTime.split(",");
            params.put("startApplyTime", time[0]);
            params.put("endApplyTime", time[1]+" 23:59:59");
        }
        params.put("referrals",referrals);
        List<Map<String, Object>> list = iCustStaticsService.starlevelDataStatics(params);

        return getDataTable(list);
    }

    /**
     * 日内部数据统计（额度）
     */
    @GetMapping("/custdebtlimitdataStatics/{timeGroup}/{deptId}")
    public TableDataInfo custdebtlimitdataStatics(@PathVariable String timeGroup, @PathVariable Long deptId) {
        //获取登录账号的角色信息
        Map<String, Object> roleMap = userInfoComm.getUserRoleCode();

        Map<String, Object> params = new HashMap<>();
        SysDept sysDept = getLoginUser().getUser().getDept();
        if (Objects.equals(sysDept.getLevel(), String.valueOf(TypeConstant.ORG_LEVEL_4))) {
            if (MapUtils.getString(roleMap, "depart_leader", "0").equals("0")) { // 业务员
                // 业务员只能看到本人的日志
                params.put("empId", getUserId());
            }
        }
        if (deptId != -1L) {
            sysDept = new SysDept();
            sysDept.setDeptId(deptId);
        }

        Long[] orgIds = userInfoComm.getSysDepts(sysDept);
        params.put("orgIds", orgIds);
        if (timeGroup != null && !timeGroup.isEmpty()) {
            String[] time = timeGroup.split(",");
            params.put("startTime", time[0]);
            params.put("endTime", time[1]+" 23:59:59");
        }

        List<Map<String, Object>> list = iCustStaticsService.custdebtlimitdataStatics(params);

        return getDataTable(list);
    }

    /**
     * 公共池数据统计
     * 20240304: 新增  --
     */
    @GetMapping("/publicCustDataStatics/{status}/{level}")
    public AjaxResult publicCustDataStatics(@PathVariable String status, @PathVariable String level) {
        Map<String, Object> result = new HashMap<String, Object>();
        //入参
        Map<String, Object> inParams = new HashMap<String, Object>();
        int rightType = userInfoComm.getRightType();

        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = userInfoComm.getDeptIds(getDeptId());
        inParams.put("deptIds", orgIds);
        inParams.put("level", level);
        inParams.put("status", status);
        List<Map<String, Object>> list = iCustStaticsService.publicCustDataStatics(inParams);
        result.put("rightType",rightType);
        result.put("list",list);
        return AjaxResult.success(result);
    }
    /**
     * 团队数据统计
     * 20240304: 新增  --
     */
    @GetMapping("/teamCustDataStatics/{status}/{level}")
    public AjaxResult teamCustDataStatics(@PathVariable String status, @PathVariable String level) {
        Map<String, Object> result = new HashMap<String, Object>();
        //入参
        Map<String, Object> inParams = new HashMap<String, Object>();
        int rightType = userInfoComm.getRightType();

        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = userInfoComm.getDeptIds(getDeptId());
        inParams.put("deptIds", orgIds);
        inParams.put("level", level);
        inParams.put("status", status);
        List<Map<String, Object>> list = iCustStaticsService.teamCustDataStatics(inParams);
        result.put("rightType",rightType);
        result.put("list",list);
        return AjaxResult.success(result);
    }
    /**
     * 拨打数据情况统计
     * 20240304: 新增  --
     */
    @GetMapping("/getCallCustDatas/{timeGroup}/{empId}/{deptId}")
    public TableDataInfo getCallCustDatas(@PathVariable String timeGroup, @PathVariable String empId, @PathVariable Long deptId) {
        //入参
        Map<String, Object> inParams = new HashMap<String, Object>();
        deptId=deptId==-1?getDeptId():deptId;
        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = userInfoComm.getDeptIds(deptId);
        inParams.put("deptIds", orgIds);
        inParams.put("empId", empId);
        if (timeGroup != null && !timeGroup.isEmpty()) {
            String[] time = timeGroup.split(",");
            inParams.put("startTime", time[0]);
            inParams.put("endTime", time[1]+" 23:59:59");
        }
        List<Map<String, Object>> list = iCustStaticsService.callCustDataStatics(inParams);

        return getDataTable(list);
    }

    /**
     * 成交客户统计报表
     * @param timeGroup
     * @param reportType 报表类型
     * @param deptId
     * @return
     */
    @GetMapping("/getTransactionDatas/{timeGroup}/{reportType}/{deptId}")
    public TableDataInfo getTransactionDatas(@PathVariable String timeGroup, @PathVariable String reportType, @PathVariable Long deptId) {
        //入参
        Map<String, Object> inParams = new HashMap<String, Object>();
        deptId=deptId==-1?getDeptId():deptId;
        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = userInfoComm.getDeptIds(deptId);
        inParams.put("deptIds", orgIds);
        inParams.put("reportType", reportType);
        if (timeGroup != null && !timeGroup.isEmpty()) {
            String[] time = timeGroup.split(",");
            inParams.put("startTime", time[0]);
            inParams.put("endTime", time[1]+" 23:59:59");
        }
        List<Map<String, Object>> list = iCustStaticsService.getTransactionDatas(inParams);

        return getDataTable(list);
    }

    /**
     * 成交客户画像
     * @param timeGroup
     * @param reportType 报表类型
     * @param deptId
     * @return
     */
    @GetMapping("/getTransactionCustPortraitDatas/{timeGroup}/{reportType}/{deptId}")
    public TableDataInfo getTransactionCustPortraitDatas(@PathVariable String timeGroup, @PathVariable String reportType, @PathVariable Long deptId) {
        //入参
        Map<String, Object> inParams = new HashMap<String, Object>();
        deptId=deptId==-1?getDeptId():deptId;
        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = userInfoComm.getDeptIds(deptId);
        inParams.put("deptIds", orgIds);
        inParams.put("reportType", reportType);
        if (timeGroup != null && !timeGroup.isEmpty()) {
            String[] time = timeGroup.split(",");
            inParams.put("startTime", time[0]);
            inParams.put("endTime", time[1]+" 23:59:59");
        }
        List<Map<String, Object>> list = iCustStaticsService.getTransactionCustPortraitDatas(inParams);

        return getDataTable(list);
    }

}
